// ActionScript file
import com.adobe.cairngorm.control.CairngormEventDispatcher;
import com.uday.kraterchat.chatclient.control.LogoutUserEvent;
import com.uday.kraterchat.chatclient.model.ChatClientModel;
import com.uday.kraterchat.chatclient.util.ImageUtil;

import flash.desktop.NativeApplication;
import flash.desktop.SystemTrayIcon;
import flash.display.Bitmap;
import flash.display.NativeMenu;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;

import mx.controls.Alert;
import mx.controls.FlexNativeMenu;
import mx.events.CloseEvent;
import mx.events.FlexNativeMenuEvent;

	private var dockImage:BitmapData;
	private var notifyImage:BitmapData;
	private var intAlertCurrImg:int = 0;
	
	private var notifyTimer:Timer = new Timer(500,0);

	private function closingApplication(evt:Event):void {
		//Don't close, so prevent the event from happening 
		evt.preventDefault();
		   
		//Check what the user really want's to do       
		Alert.buttonWidth = 110; 
		Alert.yesLabel = "Close";
		Alert.noLabel = "Minimize";
		Alert.show("Close or minimize?", "Close?", 3, this, alertCloseHandler);
	}

   // Event handler function for displaying the selected Alert button. 
   private function alertCloseHandler(event:CloseEvent):void {
      if (event.detail==Alert.YES) {
         closeApp(event);
      } else {
         dock();
      }
   }

	
	public function prepareForSystray():void {
		//Retrieve the image being used as the systray icon
		dockImage = (new ImageUtil.KraterchatIcon() as Bitmap).bitmapData;
		notifyImage = (new ImageUtil.KraterchatIconNeg() as Bitmap).bitmapData;
		notifyTimer.addEventListener(TimerEvent.TIMER,startNotification);
		createMenu();
		   
		//For windows systems we can set the systray props       //(there's also an implementation for mac's, it's similar and you can find it on the net... ;) ) 
		if (NativeApplication.supportsSystemTrayIcon){
			setSystemTrayProperties();
			//Set some systray menu options, so that the user can right-click and access functionality          //without needing to open the application          
			SystemTrayIcon(NativeApplication.nativeApplication .icon).menu = createSystrayRootMenu();
		}
	}
	
	public function createMenu():void{
		if(NativeApplication.supportsMenu){
			this.menu = new FlexNativeMenu();
			this.menu.nativeMenu.addItem(new NativeMenuItem("File"));
		}
	}

	
	private function setSystemTrayProperties():void{
    	//Text to show when hovering of the docked application icon       
		SystemTrayIcon(NativeApplication.nativeApplication .icon).tooltip = "Kraterchat";
		       
	    //We want to be able to open the application after it has been docked       
		SystemTrayIcon(NativeApplication.nativeApplication .icon).addEventListener(MouseEvent.CLICK, undock);
		       
	    //Listen to the display state changing of the window, so that we can catch the minimize       
		stage.nativeWindow.addEventListener(NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGING, nwMinimized); //Catch the minimize event 
	}
	
	private function nwMinimized(displayStateEvent:NativeWindowDisplayStateEvent):void {
	    
		//Do we have an minimize action?       //The afterDisplayState hasn't happened yet, but only describes the state the window will go to,       //so we can prevent it! 
		if(displayStateEvent.afterDisplayState == NativeWindowDisplayState.MINIMIZED) {
			//Prevent the windowedapplication minimize action from happening and implement our own minimize          //The reason the windowedapplication minimize action is caught, is that if active we're not able to          //undock the application back neatly. The application doesn't become visible directly, but only after clicking          //on the taskbars application link. (Not sure yet what happens exactly with standard minimize) 
			displayStateEvent.preventDefault();
			          
			//Dock (our own minimize) 
			dock();
		}
	}

	
	private function createSystrayRootMenu():NativeMenu{
		//Add the menuitems with the corresponding actions 
		var menu:NativeMenu = new NativeMenu();
		var openNativeMenuItem:NativeMenuItem = new NativeMenuItem("Open");
		var exitNativeMenuItem:NativeMenuItem = new NativeMenuItem("Exit");
		//What should happen when the user clicks on something...       
		openNativeMenuItem.addEventListener(Event.SELECT, undock);
		exitNativeMenuItem.addEventListener(Event.SELECT, closeApp);
		//Add the menuitems to the menu 
		menu.addItem(openNativeMenuItem);
		menu.addItem(new NativeMenuItem("",true));
		//separator 
		menu.addItem(exitNativeMenuItem);
		
		return menu;
	}
	
	public function dock():void {
		//Hide the applcation 
		stage.nativeWindow.visible = false;
		//ChatClientModel.getInstance().objChatWindow.openWindow(false);
		ChatClientModel.getInstance().blnIsMinimized = true;
		
		//Setting the bitmaps array will show the application icon in the systray 
		NativeApplication.nativeApplication .icon.bitmaps = [dockImage];
	}

	public function undock(evt:Event):void {
		//After setting the window to visible, make sure that the application is ordered to the front,       //else we'll still need to click on the application on the taskbar to make it visible 
		stage.nativeWindow.visible = true;
		ChatClientModel.getInstance().blnIsMinimized = false;
		stage.nativeWindow.orderToFront();
		if(notifyTimer.running){
			ChatClientModel.getInstance().objChatWindow.openWindow(true);
			ChatClientModel.getInstance().objChatWindow.orderInFrontOf(this);
			notifyTimer.stop();
		}
		
		       
		//Clearing the bitmaps array also clears the applcation icon from the systray 
		NativeApplication.nativeApplication .icon.bitmaps = [];
	}

	private function closeApp(evt:Event):void {
		var objChatClientModel:ChatClientModel = ChatClientModel.getInstance();
		
		objChatClientModel.blnIsApplClosed = true;
		CairngormEventDispatcher.getInstance().dispatchEvent(new LogoutUserEvent(objChatClientModel.objCurrUser));
	}
	
	private function startNotification(event:TimerEvent):void{
		if((intAlertCurrImg % 2) == 0){
			NativeApplication.nativeApplication .icon.bitmaps = [notifyImage];
		} else{
			NativeApplication.nativeApplication .icon.bitmaps = [dockImage];
		}
		intAlertCurrImg++;
	}
	
	public function notifyUser():void{
		if(ChatClientModel.getInstance().blnIsMinimized){
			notifyTimer.start();
		} else if(NativeWindow.supportsNotification){
			var nativeWindow:NativeWindow = ChatClientModel.getInstance().objChatWindow.nativeWindow;
			nativeWindow.activate();
			nativeWindow.notifyUser(NotificationType.CRITICAL);
		}
	}

	
	private function menuClicked(event:FlexNativeMenuEvent):void{
		if(event.item.@code == "1001"){
			var objChatClientModel:ChatClientModel = ChatClientModel.getInstance();
			
			objChatClientModel.blnIsApplClosed = false;
			CairngormEventDispatcher.getInstance().dispatchEvent(new LogoutUserEvent(objChatClientModel.objCurrUser));
		}
	}